<?php

/**
 * Created by PhpStorm.
 * User: raymon
 * Date: 17-8-6
 * Time: 上午11:09
 */
class Login extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper('cookie');
        $this->load->model('users_model');
    }

    public function index($info = null)
    {
        $data = array();
        $data['link_login_submit'] = site_url("login");
        //登录表单
        $login_submit = $this->input->post('login_submit');
        //登录表单是否提交
        if ($login_submit != '') {
            //各项检测
            $name = $this->input->post('id');
            $pw = md5($this->input->post('password')); //密码
            $data['input']['name'] = &$name;
            //学号与密码不能为空
            if (!empty($name) && $pw != 'd41d8cd98f00b204e9800998ecf8427e') {
                //快捷登录
                $sql = $this->users_model->login($name, $pw);
                //如果获取到的uid为空，说明用户不存在
                if (!empty($sql['id'])) {
                    //如果获取到的auth为空，说明鉴权失败，密码错误
                    if (!empty($sql['auth'])) {
                        $uid = $sql['id'];
                        $newsession = array(
                            //'ip' => md5($_SERVER["HTTP_CLIENT_IP"]),
                            'uid' => $uid,
                            //用session缓存用户资料
                            'uname' => $sql['name']
                        );
                        //登录成功，设置cookie,session,用户资料缓存
                        setcookie('uid',$uid);
                        $this->session->set_userdata($newsession);
                        //重定向到后台用户管理
                        header("Location:" . site_url("admin"));
                        //确保重定向后，后续代码不会被执行
                        exit;
                    } else {
                        $data['info'] = '密码错误！';
                    }
                } else {
                    $data['info'] = '该用户不存在!';
                }
            } else {
                $data['info'] = '用户名或密码不能为空!';
            }
        }
        //出错就会回登录页
        $this->_view('login.twig', $data, 'admin','');
    }
        public function logout(){
            delete_cookie('uid'); //清除cookie
            $this->session->unset_userdata('uid'); //清除session uid
            //重定向到首页
            header("Location:" . site_url("login"));
            //确保重定向后，后续代码不会被执行
            exit;

        }
}